package com.leonwoodstudio.endorsementclient;

import android.content.Context;
import android.content.res.Resources;
import android.os.AsyncTask;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * Created by win7 on 2017/3/15.
 */
public class SendCommandAsyncTask extends AsyncTask<Integer, Void, Integer> {
    Context context;
    boolean success;
    String remote_ip_address;
    String remote_port;
    String[] buttons;

    public SendCommandAsyncTask(Context context, String remote_ip_address, String remote_port) {
        super();
        this.context = context;
        this.remote_ip_address = remote_ip_address;
        this.remote_port = remote_port;
        success = false;
        Resources res = context.getResources();
        buttons = res.getStringArray(R.array.buttons);
    }

    protected Integer doInBackground(Integer... command_id) {
        byte[] command = Util.connectByteArray(
                Util.connectByteArray(Util.commandHead(), Util.int2ByteArray(command_id[0])),
                Util.commandTail());
        sendCommand(remote_ip_address, Integer.valueOf(remote_port), command);

        return command_id[0];
    }

    protected void onPostExecute(Integer result) {
        MainActivity activity = (MainActivity)context;
        if (success) {
            activity.status_message.setText("命令: " + buttons[result] + " 执行成功!");
        } else {
            activity.status_message.setText("命令: " + buttons[result] + " 执行失败,请检查网络和服务器端是否正常!");
        }
    }

    void sendCommand(String address, int port, byte[] command) {
        Socket socket = null;
        try {
            socket = new Socket();
            SocketAddress socketAddress = new InetSocketAddress(address, port);
            socket.connect(socketAddress, 3000);
            OutputStream os = socket.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(os);
            bos.write(command, 0, command.length);
            bos.close();
            socket.close();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}